<template>
  <a-flex gap="large" vertical>
    <HomeHeader/>
    <a-affix :offset-top="10">
      <a-input
          placeholder="点我搜索"
          size="large"
          :allow-clear="true"
          @click="showSearchModal"
      />
    </a-affix>
    <a-card v-for="group in groups" :key="group.id" class="icon_group_card">
      <a-flex gap="large" vertical>
        <a-typography-title :level="3">{{ group.name }}</a-typography-title>
        <a-flex wrap="wrap" gap="large">
          <AppIcon
              v-for="url in filteredUrlsByGroup(group.id)"
              :key="url.id"
              :url="url.url"
              :icon="url.icon"
              :name="url.name"
              :description="url.description"
              @edit="editUrl(url)"
              @delete="deleteUrl(url)"
          />
          <a-avatar
              shape="square"
              :size="64"
              @click="addUrl(group.id)"
              style="background-color: rgba(0,0,0,0.2)"
          >
            添加
          </a-avatar>
        </a-flex>
      </a-flex>
    </a-card>
  </a-flex>
  <a-modal
      v-model:open="isModalVisible"
      :zIndex="1001"
      title="添加/编辑网址"
      @ok="handleOk"
      @cancel="handleCancel"
  >
    <a-form :model="urlForm" ref="urlFormRef">
      <a-form-item
          label="网址"
          :rules="[{ required: true, message: '网址是必填项' }]"
      >
        <a-input v-model:value="urlForm.url"/>
      </a-form-item>
      <a-form-item
          label="名称"
          :rules="[{ required: true, message: '名称是必填项' }]"
      >
        <a-input v-model:value="urlForm.name"/>
      </a-form-item>
      <a-form-item label="描述">
        <a-input v-model:value="urlForm.description"/>
      </a-form-item>
      <a-form-item label="图标">
        <a-flex gap="small" horizontal>
          <a-input v-model:value="urlForm.icon"/>
          <a-button type="primary" @click="fetchIcon">自动获取</a-button>
        </a-flex>
      </a-form-item>

      <a-form-item
          label="分类"
          :rules="[{ required: true, message: '分类是必填项' }]"
      >
        <a-select v-model:value="urlForm.group_id">
          <a-select-option
              v-for="group in groups"
              :key="group.id"
              :value="group.id"
          >
            {{ group.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
  <SearchUrl
      ref="searchRefs"
      :open="searchIsModalVisible"
      @close="closeSearchModel"
      @refreshList="fetchGroups"
      @openEdit="editUrl"
  />
  <SettingModal/>
  <a-layout-footer style="text-align: center; color: black">
    {{ footer_text }}
  </a-layout-footer>
  <div class="frosted-glass" />
</template>

<script setup>
import {ref, reactive, onMounted, nextTick} from "vue";
import useThemeStore from '@/stores/modules/theme';
import * as home from "@/api/home/index";
import AppIcon from "@/components/AppIcon.vue";
import HomeHeader from "@/components/HomeHeader.vue";
import SearchUrl from "@/components/SearchUrl.vue";
import {message} from "ant-design-vue";
import SettingModal from "@/components/SettingModal.vue";

const emit = defineEmits(["refreshSearch"]);
const themeStore = useThemeStore();
const searchIsModalVisible = ref(false);
const isModalVisible = ref(false);
const footer_text = ref("Created by Ant UED");
const groups = ref([]);
const urlsByGroup = reactive({});
const urlForm = reactive({
  url: "",
  name: "",
  icon: "",
  group_id: null,
  description: "",
});
const searchValue = ref("");
const searchRefs = ref(null);

onMounted(async () => {
  footer_text.value = await fetchSettingByKey("footer");
  await fetchGroups();
  const themeColor = localStorage.getItem("theme") !== null ? localStorage.getItem("theme") : 'light';
  themeStore.changeTheme(themeColor);
});

const showSearchModal = async () => {
  searchIsModalVisible.value = true;
};
// Perform search
const editUrl = (url, search = "") => {
  Object.assign(urlForm, url);
  searchValue.value = search;
  isModalVisible.value = true;
};

const getFrostedGlassClass = () => {
  if (themeStore.isFrostedGlass) {
    if (themeStore.isDarkTheme) {
      return 'frosted-glass-dark'
    } else {
      return 'frosted-glass-light'
    }
  }
}

// Handle OK
const handleOk = async () => {
  if (urlForm.id) {
    await home.putListByGroupId(urlForm);
  } else {
    await home.addListByGroupId(urlForm);
  }
  isModalVisible.value = false;
  fetchGroups();
  // 等待 DOM 更新
  await nextTick();
  searchRefs.value.performSearch(searchValue.value);
};

// Handle cancel
const handleCancel = () => {
  isModalVisible.value = false;
};

const fetchGroups = async () => {
  try {
    await themeStore.getColorPrimary();
    const response = await home.getGroup();
    groups.value = response.data;
    groups.value.forEach((group) => {
      fetchUrlsByGroup(group.id);
    });
    const res = await home.getSettingByKey("backgroundImage_model");
    if (res.data.value) {
      themeStore.changeBackgroundImage(res.data.value);
    }
  } catch (error) {
    message.error("获取分组失败", error);
  }
};

// Fetch URLs by group ID
const fetchUrlsByGroup = async (group_id) => {
  try {
    const response = await home.getGroupByID(group_id);
    urlsByGroup[group_id] = response.data;
  } catch (error) {
    message.error(`获取分组 ${group_id} 的网址失败`, error);
  }
};

const filteredUrlsByGroup = (group_id) => {
  return urlsByGroup[group_id] || [];
};

const addUrl = (group_id) => {
  Object.assign(urlForm, {
    id: null,
    url: "",
    name: "",
    icon: "",
    description: "",
    group_id,
  });
  isModalVisible.value = true;
};

const deleteUrl = async (id) => {
  await home.delListByGroupId(id);
  fetchGroups();
};
const fetchSettingByKey = async (key) => {
  try {
    const response = await home.getSettingByKey(key);
    return response.data.value;
  } catch (error) {
    message.error(`获取 ${key} 失败`, error);
    return "";
  }
};

// Fetch icon
const fetchIcon = async () => {
  const url = urlForm.url;
  if (!url) {
    // 使用适合的消息提示方式
    message.info("请先输入网址");
    return;
  }

  try {
    const response = await home.getFavicon({url});
    if (response.code === 200 && response.data !== "") {
      urlForm.icon = response.data;
    } else {
      // 使用适合的消息提示方式
      message.info("获取图标失败: " + response.msg);
    }
  } catch (error) {
    // 使用适合的消息提示方式
    message.info("获取图标失败: " + error.message);
  }
};

// 搜索框弹窗关闭
const closeSearchModel = async () => {
  searchIsModalVisible.value = false;
  await nextTick();
  searchRefs.value.resetSearchValue();
};
</script>

<style scoped>
.icon_group_card {
  box-shadow: 0 10px 20px 4px rgba(0, 0, 0, 0.05);
}
</style>
